package com.example.administrator.u17.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.u17.R;
import com.example.administrator.u17.adapter.ZhangjieBaseAdapter;
import com.example.administrator.u17.application.MyApplication;
import com.example.administrator.u17.config.NetConfig;
import com.example.administrator.u17.db.Cllecnt;
import com.example.administrator.u17.db.MyJson;
import com.example.administrator.u17.modle.ZhangjieInfo;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.squareup.picasso.Picasso;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.db.sqlite.WhereBuilder;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;

public class ZhangJieActivity extends AppCompatActivity {

    private PullToRefreshListView pu;
    private DbManager manager;
    private List<ZhangjieInfo.DataBean.ReturnDataBean.ChapterListBean> list;
    private ZhangjieInfo.DataBean.ReturnDataBean.ComicBean mData;
    private List<ZhangjieInfo.DataBean.ReturnDataBean.OtherWorksBean> list2;
    private BaseAdapter mAdapter;
    private ListView lv;
    private View view;
    private ImageView iv, iv2, iv3;
    private TextView tv, tv2, tv3, tv4, tv5, tv6, tv7, tv8, tv9;
    private CheckBox tv10;
    private CheckBox box;
    private String title, name;
    private String id;
    private String autor;
    private String path;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_zhang_jie);
        initView();
        initData();
        setData();
        setlistener();
    }


    public void click(View view) {
        switch (view.getId()) {
            case R.id.iv_activity_zhangjie_break:
                finish();
                break;
            case R.id.iv_activity_zhangjie_shoucang:
                if (box.isChecked()) {
                    Cllecnt cllecnt = new Cllecnt();
                    cllecnt.adressid = id;
                    cllecnt.title = name;
                    cllecnt.name = autor;
                    cllecnt.path = path;
                    try {
                        manager.save(cllecnt);
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                    Toast.makeText(this, "已收藏到后宫", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        manager.delete(Cllecnt.class, WhereBuilder.b("adressid", "=", id));
                        Toast.makeText(this, "无情删除", Toast.LENGTH_SHORT).show();
                    } catch (DbException e) {
                        e.printStackTrace();
                    }
                }
                break;
            case R.id.iv_activity_zhangjie_share:
                showShare();
                break;
        }
    }

    private void showShare() {
        ShareSDK.initSDK(this);
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();
// 分享时Notification的图标和文字  2.5.9以后的版本不调用此方法
        //oks.setNotification(R.drawable.ic_launcher, getString(R.string.app_name));
        // title标题，印象笔记、邮箱、信息、微信、人人网和QQ空间使用
        oks.setTitle(name);
        // titleUrl是标题的网络链接，仅在人人网和QQ空间使用
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText(title);
        //分享网络图片，新浪微博分享网络图片需要通过审核后申请高级写入接口，否则请注释掉测试新浪微博
        oks.setImageUrl("http://f1.sharesdk.cn/imgs/2014/02/26/owWpLZo_638x960.jpg");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url仅在微信（包括好友和朋友圈）中使用
        oks.setUrl("http://sharesdk.cn");
        // comment是我对这条分享的评论，仅在人人网和QQ空间使用
        oks.setComment("我是测试评论文本");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite("ShareSDK");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");
// 启动分享GUI
        oks.show(this);
    }

    private void setlistener() {
    }

    private void setData() {
        pu.setMode(PullToRefreshBase.Mode.BOTH);
        pu.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
                //设置下拉刷新回到第一页
                list.clear();
                loadData();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
            }
        });
        pu.setAdapter(mAdapter);
    }

    private void initData() {
        list = new ArrayList<>();
        mData = new ZhangjieInfo.DataBean.ReturnDataBean.ComicBean();
        list2 = new ArrayList<>();
        mAdapter = new ZhangjieBaseAdapter(list, list2, this);
        manager = x.getDb(new DbManager.DaoConfig());
        view = View.inflate(ZhangJieActivity.this, R.layout.item_zhangjie_head, null);
        iv = (ImageView) view.findViewById(R.id.iv_item_zhangjie_header_1);
        iv2 = (ImageView) findViewById(R.id.iv_item_zhangjie_header_backgroud);
        iv3 = (ImageView) view.findViewById(R.id.iv_item_xu_down);
        tv = (TextView) view.findViewById(R.id.tv_item_zhangjie_header_title);
        tv2 = (TextView) view.findViewById(R.id.tv_item_zhangjie_header_actuer);
        tv3 = (TextView) view.findViewById(R.id.tv_item_zhangjie_header_count);
        tv4 = (TextView) view.findViewById(R.id.tv_item_zhangjie_header_type);
        tv5 = (TextView) view.findViewById(R.id.tv_item_zhangjie_header_text);
        tv6 = (TextView) view.findViewById(R.id.tv_item_zhangjie_header_yuepiao);
        tv7 = (TextView) view.findViewById(R.id.tv_item_down_down);
        tv8 = (TextView) view.findViewById(R.id.tv_item_down_read);
        tv9 = (TextView) view.findViewById(R.id.tv_item_xu_text);
        tv10 = (CheckBox) view.findViewById(R.id.tv_item_xu_sunxu);
        lv.addHeaderView(view);
        tv6.setText(getIntent().getStringExtra("count"));
        loadData();
    }

    private void initView() {
        pu = (PullToRefreshListView) findViewById(R.id.plv_activity_zhangjie);
        lv = pu.getRefreshableView();
        box = (CheckBox) findViewById(R.id.iv_activity_zhangjie_shoucang);
    }

    private void loadData() {
        final Intent intent = getIntent();
        id = intent.getStringExtra("id");
        final RequestParams p = new RequestParams(NetConfig.ZHANGJIE_PATH + id);
        x.http().get(p, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                MyJson myjson = new MyJson();
                myjson.json = result;
                myjson.path = Environment.
                        getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + "zhangjie.txt";
                try {
                    manager.delete(MyJson.class);
                    manager.save(myjson);
                } catch (DbException e) {
                    e.printStackTrace();
                }
                final ZhangjieInfo info = new Gson().fromJson(result, ZhangjieInfo.class);
                mData = info.data.returnData.comic;
                for (ZhangjieInfo.DataBean.ReturnDataBean.OtherWorksBean o : info.data.returnData.otherWorks) {
                    list2.add(o);
                }
                for (int i = info.data.returnData.chapter_list.size() - 1; i >= 0; i--) {
                    list.add(info.data.returnData.chapter_list.get(i));
                }
                path = mData.cover;
                Picasso.with(ZhangJieActivity.this).load(mData.cover).into(iv);
                Picasso.with(ZhangJieActivity.this).load(mData.cover).into(iv2);
                tv.setText(mData.name);
                name = mData.name;
                autor = mData.author.name;
                tv2.setText("" + mData.author.name);
                final StringBuilder sb = new StringBuilder();
                for (int j = 0; j < mData.theme_ids.size(); j++) {
                    sb.append(mData.theme_ids.get(j) + " ");
                }
                tv4.setText(sb.toString());
                title = mData.description;
                final MyApplication application = (MyApplication) getApplication();
                tv5.setText(mData.description);
                tv5.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent1 = new Intent(ZhangJieActivity.this, InfoActivity.class);
                        intent1.putExtra("text", mData.description);
                        intent1.putExtra("name", mData.author.name);
                        intent1.putExtra("path", mData.author.avatar);
                        intent1.putExtra("cate_id", mData.cate_id);
                        intent1.putExtra("id", mData.author.id);
                        intent1.putExtra("last_update_week", mData.last_update_week);
                        intent1.putExtra("sb", sb.toString());
                        intent1.putExtra("count", getIntent().getStringExtra("count"));
                        startActivity(intent1);
                    }
                });
                tv7.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {

                    }
                });
                if (application.index != null) {
                    tv8.setText("继续阅读");
                }
                tv8.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent intent = new Intent(ZhangJieActivity.this, ReadActivity.class);
                        if (application.index == null) {
                            tv8.setText("继续阅读");
                            intent.putExtra("id", list.get(0).chapter_id);
                        } else {
                            intent.putExtra("id", application.index);
                        }
                        startActivity(intent);
                    }
                });
                tv9.setText("更新到" + list.get(0).name);
                application.adressid = id;
                application.title = name;
                application.name = autor;
                application.path = path;
                tv10.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                        if (b) {
                            list.clear();
                            for (ZhangjieInfo.DataBean.ReturnDataBean.ChapterListBean c : info.data.returnData.chapter_list) {
                                list.add(c);
                            }
                            mAdapter.notifyDataSetChanged();
                            tv10.setText("正序");
                            iv3.setImageResource(R.mipmap.icon_arrow_up);
                        } else {
                            list.clear();
                            for (int i = info.data.returnData.chapter_list.size() - 1; i >= 0; i--) {
                                list.add(info.data.returnData.chapter_list.get(i));
                            }
                            tv10.setText("倒序");
                            iv3.setImageResource(R.mipmap.icon_arrow_down);
                            mAdapter.notifyDataSetChanged();
                        }
                    }
                });

                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                String path = Environment.
                        getExternalStorageDirectory().getAbsolutePath()
                        + File.separator + "zhangjie.txt";
                List<MyJson> myjson = null;
                try {
                    myjson = manager.selector(MyJson.class).where("path", "=", path).findAll();
                } catch (DbException e) {
                    e.printStackTrace();
                }
                final ZhangjieInfo info = new Gson().fromJson(myjson.get(0).json, ZhangjieInfo.class);
                mData = info.data.returnData.comic;
                for (ZhangjieInfo.DataBean.ReturnDataBean.OtherWorksBean o : info.data.returnData.otherWorks) {
                    list2.add(o);
                }
                for (ZhangjieInfo.DataBean.ReturnDataBean.ChapterListBean c : info.data.returnData.chapter_list) {
                    list.add(c);
                }
                path = mData.cover;
                Picasso.with(ZhangJieActivity.this).load(mData.cover).into(iv);
                Picasso.with(ZhangJieActivity.this).load(mData.cover).into(iv2);
                tv.setText(mData.name);
                name = mData.name;
                autor = mData.author.name;
                tv2.setText("" + mData.author.name);
                StringBuilder sb = new StringBuilder();
                for (int j = 0; j < mData.theme_ids.size(); j++) {
                    sb.append(mData.theme_ids.get(j) + " ");
                }
                tv4.setText(sb.toString());
                title = mData.description;
                tv5.setText(mData.description);
                tv5.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Bundle bundle = new Bundle();
                        Intent intent1 = new Intent(ZhangJieActivity.this, InfoActivity.class);
                        intent1.putExtra("text", mData.description);
                        intent1.putExtra("name", mData.author.name);
                        intent1.putExtra("path", mData.author.avatar);
                        intent1.putExtra("cate_id", mData.cate_id);
//                        intent1.putExtras(bundle);
                        startActivity(intent1);
                    }
                });
                tv7.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {


                    }
                });
                tv8.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                    }
                });
                tv9.setText("更新到" + list.get(list.size() - 1).name);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onCancelled(CancelledException cex) {
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFinished() {
                mAdapter.notifyDataSetChanged();
                pu.onRefreshComplete();
            }
        });

    }
}
